package com.ktjiaoyu.ktmall.dao.impl;

import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.dao.ProductDao;
import com.ktjiaoyu.ktmall.entity.Product;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl extends BaseDao implements ProductDao {
    @Override
    public List<Product> findList(String title, Long categoryId, int pageNo, int pageSize) throws SQLException {
        StringBuilder sql = new StringBuilder("select * from kt_product where is_deleted = 0 ");
        List<Object> params = new ArrayList<>();
        if (title != null && !title.isEmpty()){
            sql.append("and title like ?");
            params.add("%" + title + "%");

        }
        if (categoryId != null && categoryId > 0){
            sql.append("and find_in_set(?,category_path)");
            params.add(categoryId);
        }
        sql.append("order by create_time desc limit ?,?");
        params.add((pageNo - 1) * pageSize);
        params.add(pageSize);
        return executeQuery(sql.toString(), rs -> {
            List<Product> list = new ArrayList<>();
            try {
                while (rs.next()) {
                    list.add(extractProduct(rs));
                }
            } catch (SQLException e) {

                e.printStackTrace();
            }
            return list;
        }, params.toArray());
    }

    @Override
    public int insert(Product entity) throws SQLException {
        // 修正1：统一用反引号包裹所有字段，补全缺失的逗号
        String sql = "INSERT INTO `ktmall`.`kt_product`(" +
                "`title`, `subtitle`, `category_id`, `category_path`, `brand`, " +
                "`main_image`, `images`, `description`, `price`, `original_price`, " +
                "`stock`, `sales`, `status`, `create_time`, `update_time`" +  // 补全逗号，修正字段格式
                ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now(), now());";  // 调整参数数量匹配字段
        try {
            // 修正2：sales参数使用entity.getSales()，并补全参数顺序
            return executeUpdate(sql,
                    entity.getTitle(),
                    entity.getSubtitle(),
                    entity.getCategory_id(),
                    entity.getCategory_path(),
                    entity.getBrand(),
                    entity.getMain_image(),
                    entity.getImages(),
                    entity.getDescription(),
                    entity.getPrice(),
                    entity.getOriginal_price(),
                    entity.getStock(),
                    entity.getSales() != null ? entity.getSales() : 0,  // 修正为getSales()
                    entity.getStatus() != null ? entity.getStatus() : 0  // 补充status的默认值处理
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Product entity) throws SQLException {
        StringBuilder sql = new StringBuilder("UPDATE `kt_product` SET ");
        List<Object> params = new ArrayList<>();
        if (entity.getTitle() != null && !entity.getTitle().isEmpty()){
            sql.append(" title = ? ,");
            params.add(entity.getTitle());
        }
        if (entity.getSubtitle() != null && !entity.getSubtitle().isEmpty()){
            sql.append(" subtitle = ? ,");
            params.add(entity.getSubtitle());
        }
        if (entity.getCategory_id() != null && entity.getCategory_id() > 0){
            sql.append(" category_id = ? ,");
            params.add(entity.getCategory_id());
        }
        if (entity.getCategory_path() != null && !entity.getCategory_path().isEmpty()){
            sql.append(" category_path = ? ,");
            params.add(entity.getCategory_path());
        }
        if (entity.getBrand() != null && !entity.getBrand().isEmpty()){
            sql.append(" brand = ? ,");
            params.add(entity.getBrand());
        }
        if (entity.getMain_image() != null && !entity.getMain_image().isEmpty()){
            sql.append(" main_image = ? ,");
            params.add(entity.getMain_image());
        }
        if (entity.getImages() != null && !entity.getImages().isEmpty()){
            sql.append(" images = ? ,");
            params.add(entity.getImages());
        }
        if (entity.getDescription() != null && !entity.getDescription().isEmpty()){
            sql.append(" description = ? ,");
            params.add(entity.getDescription());
        }
        if (entity.getPrice() != null && entity.getPrice() > 0){
            sql.append(" price = ? ,");
            params.add(entity.getPrice());
        }
        if (entity.getOriginal_price() != null && entity.getOriginal_price() > 0){
            sql.append(" original_price = ? ,");
            params.add(entity.getOriginal_price());
        }
        if (entity.getStock() != null && entity.getStock() > 0){
            sql.append(" stock = ? ,");
            params.add(entity.getStock());
        }
        if (entity.getSales() != null && entity.getSales() > 0){
            sql.append(" sales = ? ,");
            params.add(entity.getSales());
        }
        if (entity.getStatus() != null && entity.getStatus() > 0){
            sql.append(" status = ? ,");
            params.add(entity.getStatus());
        }
        sql.append(" update_time = now() where id = ?");
        params.add(entity.getId());

        return executeUpdate(sql.toString(), params.toArray());
    }

    @Override
    public Product findById(Long id) throws SQLException {
        String sql = "select * from kt_product where id = ? and is_deleted = 0";
        List<Product> list = executeQuery(sql, rs -> {
            List<Product> l = new ArrayList<>();
            try {
                if (rs.next()) {
                    l.add(extractProduct(rs));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return l;
        }, id);
        return list.isEmpty() ? null : list.get(0);
    }

    private Product extractProduct(ResultSet rs) {
        try {
            Product product = new Product();
            product.setId(rs.getLong("id"));
            product.setTitle(rs.getString("title"));
            product.setSubtitle(rs.getString("subtitle"));
            product.setCategory_id(rs.getLong("category_id"));
            product.setCategory_path(rs.getString("category_path"));
            product.setBrand(rs.getString("brand"));
            product.setMain_image(rs.getString("main_image"));
            product.setImages(rs.getString("images"));
            product.setDescription(rs.getString("description"));
            product.setPrice(rs.getDouble("price"));
            product.setOriginal_price(rs.getDouble("original_price"));
            product.setStock(rs.getInt("stock"));
            product.setSales(rs.getInt("sales"));
            product.setStatus(rs.getInt("status"));
            product.setIs_deleted(rs.getInt("is_deleted"));
            product.setCreate_time(rs.getDate("create_time"));
            product.setUpdate_time(rs.getDate("update_time"));
            return product;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int count(String title, Long categoryId) throws SQLException {
        StringBuilder sql = new StringBuilder("select count(id) from kt_product where is_deleted = 0 ");
        List<Object> params = new ArrayList<>();
        if (title != null && !title.isEmpty()){
            sql.append("and title like ?");
            params.add("%" + title + "%");

        }
        if (categoryId != null && categoryId > 0){
            sql.append("and find_in_set(?,category_path)");
            params.add(categoryId);
        }
        return executeQuery(sql.toString(), rs -> {
            try {
                if (rs.next()) {
                    return rs.getInt(1);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return 0;
        }, params.toArray());
    }

    @Override
    public int updateStatus(Long id, Integer status) throws SQLException {
        String sql = "update kt_product set status = ? where id = ?";
        return executeUpdate(sql, status, id);
    }

    @Override
    public int delete(Long id) throws SQLException {
        String sql = "update kt_product set is_deleted = 1 where id = ?";
        return executeUpdate(sql, id);
    }
}
